<?php

/**
 * JingYao-backend
 *
 * @link     https://gitee.com/wang-zhihui-release/jingyao-backend
 * @apiDocument https://gitee.com/wang-zhihui-release/jingyao-backend/wikis/
 */

use App\Models\AdminLog;
use App\Models\AdminUser;
use Illuminate\Database\Eloquent\Model;

function renderErrorJson($errno = 0, $msg = '', $data = [])
{
    $json = [
        'error_code' => $errno,
        'result_data' => $data,
        'error_message' => $msg,
    ];
    return sendJson($json);
}

function renderSuccessJson($data = null, $errno = 0, $msg = 'success')
{
    if (is_null($data)) {
        $data = new stdClass();
    }
    $json = [
        'error_code' => $errno,
        'result_data' => $data,
        'error_message' => $msg,
    ];
    return sendJson($json);
}

function sendJson($array)
{
    if (isset(request()->header()['x-show-error'])) {
        return response($array, 200, [
            'X-SHOW-ERROR' => 1,
        ]);
    }
    return response()->json($array);
}

function makeNameFromPhone($phone)
{
    $first = substr($phone, 0, 3);
    $end = substr($phone, -4);

    return sprintf('%s***%s', $first, $end);
}

function adminLog(Model $model, int $type, string $message)
{
    if (config('app.env') == 'testing' || config('app.env') == 'local') {
        return true;
    }
    try {
        $userId = request()->input('user_id');
        /** @var AdminUser $user */
        $user = AdminUser::query()->find($userId);
        AdminLog::query()->create([
            'user_id' => $user->id,
            'user_role' => $user->admin_role_id,
            'ip' => request()->ip(),
            'exec_type' => $type,
            'table' => $model->getTable(),
            'message' => $message,
            'exec_time' => time(),
        ]);
    } catch (\Exception $exception) {
        \Illuminate\Support\Facades\Log::error($exception->getMessage());
        throw new \App\Exceptions\ApiException('log error', 1);
    }
}

function adminLoginLog(Model $user, int $type, string $message)
{
    AdminLog::query()->create([
        'user_id' => $user->id,
        'user_role' => $user->admin_role_id,
        'ip' => request()->ip(),
        'exec_type' => $type,
        'table' => 'users',
        'message' => $message,
        'exec_time' => time(),
    ]);
}

function formatImageUrls(string $images): array
{
    // 随便定义的值 反正肯定比 5 大
    if (strlen($images) < 5) {
        return [];
    }
    $imageUrls = explode(',', $images);
    foreach ($imageUrls as &$imageUrl) {
        if (substr($imageUrl, 0, 4) != 'http') {
            $imageUrl = config('app.url') . $imageUrl;
        }
    }
    return $imageUrls;
}
function formatReImageUrls(string $re_images): array
{
    // 随便定义的值 反正肯定比 5 大
    if (strlen($re_images) < 5) {
        return [];
    }
    $imageUrls = explode(',', $re_images);
    foreach ($imageUrls as &$imageUrl) {
        if (substr($imageUrl, 0, 4) != 'http') {
            $imageUrl = config('app.url') . $imageUrl;
        }
    }
    return $imageUrls;
}
function caleRenderScore(float $score)
{
    $clacScore = $score * 100;
    $min = $clacScore % 100;

    $big = $clacScore - $min;
    $resMin = 0;
    if ($min <= 40) {
        $resMin = 0;
    }
    if ($min > 40 && $min < 80) {
        $resMin = 50;
    }
    if ($min >= 80) {
        $resMin = 100;
    }
    return round(($big + $resMin) / 100, 2);
}

function helpXcxRenderScore(float $score)
{
    $res = [0, 0, 0, 0, 0];
    foreach ($res as $index => &$s) {
        if ($score / ($index + 1) >= 1) {
            $s = 3; // 满
            continue;
        }
        if (($index + 1) - $score == 0.5) {
            $s = 2; // 半
            continue;
        }
        if ($index + 1 > $score) {
            $s = 1; // 空
            continue;
        }
    }
    return $res;
}

function checkArrayExistsInArray(array $allArray, array $array, string $key)
{
    foreach ($allArray as $arr) {
        if ($arr[$key] == $array[$key]) {
            return true;
        }
    }
    return false;
}

function checkInLocation(string $latitude, string $longitude)
{
    return $longitude >= 116.581099 && $longitude <= 116.639603 && $latitude >= 39.978453 && $latitude <= 40.00723;
}
